﻿using ACGN.Application.ProductTypes;
using ACGN.Application.ProductTypes.Dtos;
using ACGN.Core.Models;
using ACGN.Core.Repository;
using ACGN.Mvc.Controllers;
using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace ACGN.MVC.Areas.Admin.Controllers
{
    [Area("Admin")]
    public class ProTypeController : BaseController
    {
        private readonly ILogger<ProTypeController> _logger;
        private readonly IRepository<ProType, int> _repository;
        private readonly IProductTypeService _productTypeService;
        private readonly IMapper _mapper;

        public ProTypeController(ILogger<ProTypeController> logger,
            IRepository<ProType, int> repository,
            IProductTypeService productTypeService,
            IMapper mapper
            )
        {
            _logger = logger;
            _repository = repository;
            _productTypeService = productTypeService;
            _mapper = mapper;
        }
        public IActionResult Index()
        {
            return View();
        }
        public async Task<IActionResult> List(ProductTypeInputDto input)
        {
            var newsflashtype = await _productTypeService.GetPageResult(input);
            return Json(ListResult(_mapper.Map<List<ProType>>(newsflashtype.Data), newsflashtype.TotalCount));
        }
        public IActionResult Add()
        {
            return View();
        }
        [HttpPost]
        public async Task<ActionResult<ProType>> AddProType(ProType proType)
        {
            await _repository.InsertAsync(proType);
            return CreatedAtAction(nameof(List), new { id = proType.TId }, proType);
        }
        public async Task<IActionResult> Edit(int tId)
        {
            ProType proType = await _repository.FirstOrDefaultAsync(s => s.TId == tId);
            return View(_mapper.Map<ProType>(proType));
        }
        [HttpPost]
        public async Task<ActionResult> EditProType(int tId, ProType proType)
        {
            if (tId != proType.TId)
            {
                return Json(AjaxResult(false));
            }
            await _repository.UpdateAsync(proType);
            return Json(AjaxResult(true));
        }
        public async Task<ActionResult> Delete(int TId, ProType proType)
        {
            if (TId != proType.TId)
            {
                return Json(AjaxResult(false));
            }
            await _repository.DeleteAsync(proType);
            return Json(AjaxResult(true));
        }
    }
}
